package com.lysb.core.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public final class JsonUtil {
    private final static ObjectMapper MAPPER = new ObjectMapper();

    public static ObjectMapper instance() {
        return MAPPER;
    }

    static {
        // 允许序列化空的POJO类
        MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
        // 把java.util.Normal, Calendar输出为数字（时间戳）
        MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        // 在遇到未知属性的时候不抛出异常
        MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        // 强制JSON 空字符串("")转换为null对象值:
        MAPPER.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        // 空的对象不要转到json之中
        MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    /**
     * 将对象转为json
     *
     * @param obj
     * @return
     * @throws JsonProcessingException
     */
    public static String toJson(Object obj) throws JsonProcessingException {
        return MAPPER.writeValueAsString(obj);
    }

    /**
     * 将json字符串转为对象
     *
     * @param json
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T fromJson(String json, TypeReference valueTypeRef) throws IOException {
        return (T) MAPPER.readValue(json, valueTypeRef);
    }

    /**
     * 将json字符串转为对象
     *
     * @param json
     * @param <T>
     * @return
     * @throws IOException
     */
    public static <T> T fromJson(String json, Class<T> tClass) throws IOException {
        return MAPPER.readValue(json, tClass);
    }

    public static <T>T fromJson(String json,Class<?> parametrized, Class<?>... parameterClasses) throws IOException {
        JavaType javaType = JsonUtil.instance().getTypeFactory().constructParametricType(parametrized, parameterClasses);
        return MAPPER.readValue(json, javaType);
    }
}
